<?php

namespace app\api\controller;

use app\admin\model\AdminLog;
use app\admin\model\course\Section;
use app\admin\model\course\UserCourse;
use app\admin\model\course\UserSection;
use app\admin\model\CourseContent;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use Exception;
use fast\Random;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';
    protected $user;

    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->auth->getUser();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['user_info' => $this->auth->getUser()]);
    }
    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        $card = $this->request->request('card');
        $avatar = $this->request->request('avatar');

//        $code = $this->request->request('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
//        $ret = Sms::check($mobile, $code, 'register');
//        if (!$ret) {
//            $this->error(__('Captcha is incorrect'));
//        }
        $ret = $this->auth->register($username, $password, $email, $mobile, ['avatar' => $avatar, 'card' => $card, 'nickname' => $nickname]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $card = $this->request->request('card');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->card = $card;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
//        $captcha = $this->request->request("captcha");

        $image = $this->request->request("image");

        if (!$newpassword || !$image) {
            $this->error(__('Invalid parameters'));
        }
//        if (!$newpassword || !$captcha) {
//            $this->error(__('Invalid parameters'));
//        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            //检测人脸
            $res = \app\common\model\User::usercontrast($this->request->domain().$image,$this->request->domain().$user->avatar);
            if($res['code'] == 1){
                $this->error(__($res['msg']));
            }

//            $ret = Sms::check($mobile, $captcha, 'resetpwd');
//            if (!$ret) {
//                $this->error(__('Captcha is incorrect'));
//            }
//            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
//            $ret = Ems::check($email, $captcha, 'resetpwd');
//            if (!$ret) {
//                $this->error(__('Captcha is incorrect'));
//            }
//            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    //用户课程信息
    public function usercourse()
    {
        $course_id = $this->request->request('course_id');
        if (!$course_id) {
            $this->error(__('Invalid parameters'));
        }

        $usercourse = UserCourse::get($course_id,'coursecontent');//用户课程信息
        $this->success('返回成功', [
            'usercourse' => $usercourse,
        ]);
    }
    //创建用户课程信息
    public function addusercourse()
    {
        $coursecontent_id = $this->request->request('coursecontent_id');
        if (!$coursecontent_id) {
            $this->error(__('Invalid parameters'));
        }
        $user = $this->auth->getUser();

        $ret = UserCourse::get(['user_id' => $user->id,'coursecontent_id' =>$coursecontent_id ]);

        if($ret){
            $this->error(__('已报名'));
        }

        Db::startTrans();
        try {
//            $order = \app\admin\model\Order::get($order_id);
            $data = [
                'order_id' => 0,
                'coursecontent_id' => $coursecontent_id,
                'user_id' => $user->id,
            ];

            UserCourse::create($data);//创建

            $list = Section::all(['coursecontent_id' => $coursecontent_id]);

            foreach ($list as $v){
                //创建用户课程章节信息
                $data = [
                    "user_id" => $this->user->id,
                    "coursecontent_id" => $coursecontent_id,
                    "section_id" => $v->id
                ];
                UserSection::create($data);
            }

            Db::commit();
        }catch (\think\Exception $e){
            Db::rollback();
            $this->error(__($e->getMessage()));
        }

        $this->success(__('创建成功'));
    }
    //用户课程
    public function usercourselist()
    {
        $limit = $this->request->request('limit') ? $this->request->request('limit') : 10;//长度
        $page = $this->request->request('page');//当前页数
        $status = $this->request->request('status') ? $this->request->request('status') : 0;//学习状态

        $model_user = new UserCourse();

        $where = ['study_status' => $status, 'user_id' => $this->user->id];
        $list = $model_user
            ->with(["coursecontent"])
            ->where($where)
            ->limit($limit,$page)->select();

        foreach ($list as $v){
            //学习课程总时长
            $v->time_sum = UserSection::getUserSectionTime($v->coursecontent_id,$this->user->id);
            //课程章节总数
            $v->section_count = Section::getSectionCount($v->coursecontent_id);
        }

        $total = $model_user->where($where)->count();
        $row = ceil($total / $limit) ;

        $count1 = $model_user->where(['study_status' => 0, 'user_id' => $this->user->id])->count();//正在学习数量
        $count2 = $model_user->where(['study_status' => 1, 'user_id' => $this->user->id])->count();//完成学习数量

        $this->success('返回成功',[
            "total" => $total,
            "row" => $row,
            "row_count" => $list,
            "count1" => $count1,
            "count2" => $count2,
        ]);
    }
    //认证用户当前课程章节照片
    public function checksection()
    {
        $image = $this->request->request('image');//图片
        $section_id = $this->request->request('section_id');//章节ID
        if(!$image){
            $this->error(__('请上传图片'));
        }
        if(!$section_id){
            $this->error(__('Invalid parameters'));
        }

        //检测人脸
//        $res = \app\common\model\User::usercontrast($this->request->domain().$image,$this->request->domain().$this->user->avatar);
//        $check_status = 0;
//        if($res['code'] == 1){
//            $this->error(__($res['msg']));
//        }else{
//            $check_status = 1;
//        }

        $check_status = 1;

        //用户课程章节信息
        $where = ['user_id' => $this->user->id, 'section_id' => $section_id];
        $usersection = UserSection::get($where);
        if(!$usersection){
            //创建用户课程章节信息
            $data = [
                "user_id" => $this->user->id,
                "section_id" => $section_id,
                "image" => $image,
                "studytime" => 0,
                "check_status" => $check_status,
            ];
            $result = UserSection::create($data);
            $this->success('错误');
        }
        //更新审核状态
        $result = UserSection::update(['check_status' => $check_status,'image' => $image],$where);
        if($result){
            $this->success('认证成功',["usersection" => UserSection::get($where)]);
        }else{
            $this->success('创建失败');
        }
    }

    //用户课程章节确认完成
    public function sectionover()
    {
        $section_id = $this->request->request('section_id');//章节ID
        $time = $this->request->request('time');//章节ID
        if(!$section_id){
            $this->error(__('Invalid parameters'));
        }
        //用户课程章节信息
        $where = ['user_id' => $this->user->id, 'section_id' => $section_id];
        $usersection = UserSection::get($where);
        if($usersection->check_status == 0){
            $this->error(__('未审核'));
        }
        //更新学习状态
        $data = [
            'progress'  => 100,
            'studytime' => $time,
            'study_status'  => 1
        ];
        $result = UserSection::update($data,$where);
        if($result){
            $this->success('操作成功');
        }else{
            $this->success('操作失败');
        }
    }
    //学习记录
    public function userstudy()
    {
        $coursecontent_id = $this->request->request('coursecontent_id');//课程内容ID
        if(!$coursecontent_id){
            $this->error(__('Invalid parameters'));
        }
        //章节信息
        $section_list = Section::all(['coursecontent_id' => $coursecontent_id]);
        $user_section_list = [];
        foreach ($section_list as $v){
            $info = UserSection::get(['user_id' => $this->user->id, 'section_id' => $v->id]);
            if($info){
                $data = [
                    'section_name' => $v->name,
                    'image' => $info->image,
                    'studytime' => $info->studytime,
                    'study_status' => $info->study_status,
                    'study_status_text' => $info->study_status_text
                ];
            }else{
                $data = [
                    'section_name' => $v->name,
                    'image' => '',
                    'studytime' => '',
                    'study_status' => '',
                ];
            }
            $user_section_list[]= $data;
        }

        $this->success('返回成功',[
            'coursecontent' => UserCourse::get(['coursecontent_id' => $coursecontent_id],'coursecontent'),
            'user_section_list' => $user_section_list
        ]);
    }
    //更新用户学习时长
    public function updatstudytime()
    {
        $section_id = $this->request->request('section_id');//课程章节ID
        $studytime = $this->request->request('studytime');//学习时长

//        $where = ['section_id' => $section_id, 'user_id' => $this->user->id];

//        $info = UserSection::get($where);

        $where = ['id' => $section_id];

        $info = Section::get($where);

        if(!$info){
            $this->error(__('Invalid parameters'));
        }

        $where1 = ['section_id' => $section_id, 'user_id' => $this->user->id];

        $info1 = UserSection::get($where1);

        if(!$info1){
            $data = [
                'user_id' => $this->user->id,
                'coursecontent_id' => $info->coursecontent_id,
                'section_id' => $section_id,
                'studytime' => $studytime,
                'check_status' => 1
            ];
            $result = UserSection::create($data);
        }else{
            $result = $info1->allowField(true)->save(['studytime' => $studytime]);
        }

        if($result){
            $this->success('更新成功');
        }else{
            $this->error('更新失败');
        }

    }
    //用户课程章节
    public function usersectionlist()
    {

        $coursecontent_id = $this->request->request('coursecontent_id'); //获取课程

        if (!$coursecontent_id) {
            $this->error(__('Invalid parameters'));
        }

        $list = Section::all(['coursecontent_id' => $coursecontent_id]);
        $data = [];
        foreach ($list as $v){
//            $info = UserSection::get(['section_id' => $v->id, 'user_id' => $this->user->id]);
//            if(!$info){
//                continue;
//            }
            $data[] = [
                'section_id' => $v->id,
                'section_name' => $v->name,
                'section_image' => $v->image,
                'progress' => 0,//$info->progress,
                'study_time' =>0, //$info->studytime,
                'study_status' =>0,// $info->study_status_text,
            ];
        }
        $this->success('返回成功', [
            'list' => $data,
            'coursecontent' => \app\admin\model\course\CourseContent::get($coursecontent_id)]);
    }
    //用户课程信息
    public function sectiondetails()
    {
        $id = $this->request->request('id'); //获取章节信息
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        $this->success('返回成功', [
//            'sectioninfo' => UserSection::get(['section_id' => $id, 'user_id' => $this->user->id],'section')
            'sectioninfo' => Section::get(['id' => $id])
        ]);
    }
    //检测用户报名课程重复
    public function usercoursereuse()
    {
        $coursecontent_id = $this->request->request('coursecontent_id');//课程内容ID

        if(!$coursecontent_id){
            $this->error(__('Invalid parameters'));
        }

        $ret = UserCourse::get(['coursecontent_id' => $coursecontent_id, 'user_id' => $this->user->id]);

        if(!$ret){
            $this->success('返回成功');
        }else{
            $this->error('当前课程已报名');
        }
    }
}